#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：linux.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/21 上午8:58 
"""

import fcntl
import signal
from pathlib import Path


class LinuxPlatform:
	@staticmethod
	def create_lock(lock_path: Path):
		"""创建跨进程文件锁"""
		lock_file = lock_path.open("w")
		try:
			fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
			return lock_file
		except BlockingIOError:
			raise RuntimeError("Another instance is already running")

	@staticmethod
	def register_signals(handler):
		"""注册系统信号处理"""
		signal.signal(signal.SIGTERM, handler)
		signal.signal(signal.SIGHUP, handler)  # 配置重载
		signal.signal(signal.SIGUSR1, handler)  # 自定义信号

	@staticmethod
	def get_system_paths():
		"""获取系统标准路径"""
		return {
			"config": Path("/etc/file_monitor"),
			"logs": Path("/var/log/file_monitor"),
			"runtime": Path("/var/run/file_monitor.pid")
		}

	@staticmethod
	def create_watcher(callback):
		"""使用inotify实现实时监控"""
		from inotify_simple import INotify, flags
		inotify = INotify()
		watch_flags = flags.CREATE | flags.DELETE | flags.MODIFY

		def watch_loop():
			for path in self.config["watch_paths"]:
				inotify.add_watch(path, watch_flags)
			while True:
				for event in inotify.read():
					callback(event)

		return watch_loop
